package org.example.lock;

import org.example.thread.CalCount;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    private static int count = 0;
    public static void main(String[] args) {
        //创建锁对象
        Lock lock = new ReentrantLock(true);

        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                try {
                    lock.tryLock(1000, TimeUnit.MICROSECONDS);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                count++;
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName()+"已经运行完毕");
        });
        thread.start();
        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                try {
                    boolean b = lock.tryLock(1000, TimeUnit.MICROSECONDS);
                    System.out.println(b);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                count++;
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName()+"已经运行完毕");
        });
        thread2.start();
        Thread thread3 = new Thread(() -> {
            for (int i = 0; i < 100000; i++) {
                lock.lock();
                count++;
                lock.unlock();
            }
            System.out.println(Thread.currentThread().getName()+"已经运行完毕");
        });
        thread3.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(count);
    }
}
